from fastapi import FastAPI, HTTPException, Request, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from passlib.context import CryptContext
from models import Base, User, Userinfo

# 数据库配置
DATABASE_URL = "sqlite:///db.sqlite3"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 加密密钥
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI()

# 设置模板目录
templates = Jinja2Templates(directory="templates")

@app.get('/')
async def index():
    return "Welcome to the User Management System!"

@app.post('/register')
async def register(request: Request, username: str = Form(...), password: str = Form(...), userlevel: int = Form(default=1), name: str = Form(...), email: str = Form(...)):
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username).first()
        if user:
            db.close()
            raise HTTPException(status_code=400, detail="Username already registered")
        hashed_password = pwd_context.hash(password)
        user = User(username=username, userpass=hashed_password, userlevel=userlevel, name=name, email=email)
        db.add(user)
        userinfo = Userinfo(userid=user.id, name=name, email=email)
        db.add(userinfo)
        db.commit()
        db.close()
        # 注册成功后重定向到登录页面
        return RedirectResponse(url="/login")
    finally:
        db.close()

@app.post('/login')
async def login(request: Request, username: str = Form(...), password: str = Form(...)):
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username).first()
        if not user or not pwd_context.verify(password, user.userpass):
            # 登录失败，将错误消息传递给登录页面
            db.close()
            return templates.TemplateResponse("login.html", {"request": request, "error_message": "Invalid credentials"})
        db.close()
        # 登录成功，可以在这里实现跳转到用户主页或其他逻辑
        return {"message": f"Logged in as {user.name}"}
    finally:
        db.close()

@app.get('/register')
async def register_page(request: Request):
    return templates.TemplateResponse("register.html", {"request": request})

@app.get('/login')
async def login_page(request: Request, error_message: str = None):
    return templates.TemplateResponse("login.html", {"request": request, "error_message": error_message})